package com.cardone.parse;

import com.cardone.common.util.MapperUtils;
import com.cardone.context.ContextHolder;
import com.cardone.context.function.Execution2Function;
import lombok.Setter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * Created by c100000002 on 15-2-2.
 */
public class JsonScoreParse implements Execution2Function<Map<String, ?>, String, Map<String, ?>> {
    @Setter
    private String groupsKey = "groups";

    @Override
    public Map<String, ?> execution(String json, Map<String, ?> itemMap) {
        if (MapUtils.isEmpty(itemMap)) {
            return null;
        }

        Map<String, Object> map = MapperUtils.fromJsonForMap(json);

        Object groups = MapUtils.getObject(map, groupsKey);

        if (groups == null || !(groups instanceof Map)) {
            return null;
        }

        Map<String, String> groupsMap = (Map<String, String>) groups;

        String id = MapUtils.getString(map, "id");

        if (StringUtils.isBlank(id)) {
            return null;
        }

        Object execution2FunctionObject = ContextHolder.getBean(id);

        if (execution2FunctionObject == null) {
            return null;
        }

        Execution2Function<Map<String, ?>, Map<String, String>, Map<String, ?>> execution2Function = (Execution2Function<Map<String, ?>, Map<String, String>, Map<String, ?>>) execution2FunctionObject;

        Map<String, ?> executionMap = execution2Function.execution(groupsMap, itemMap);

        return executionMap;
    }
}
